package com.realgodo.site.service.application;

import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.hibernate.DefaultEntityManager;

import com.realgodo.site.entity.application.music.Music;

import edu.emory.mathcs.backport.java.util.Arrays;


@Service
@Transactional
public class MusicManager extends DefaultEntityManager<Music, Long> {
	
	@Autowired
	private SessionFactory sessionFactory;
	
	/**
	 * 获得个人音乐列表
	 * @param spaceId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Music> getPersonalList(Long spaceId){
		Criteria c = sessionFactory.getCurrentSession().createCriteria(Music.class);
		c.add(Restrictions.eq("space.id", spaceId));
		c.addOrder(Order.desc("id"));
		return c.list();
	}

	/**
	 * 获得个人音乐分野列表
	 * @param spaceId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public Page<Music> find(int pageSize,Map<String,Object> param){
		Page<Music> page=new Page<Music>(pageSize);
		Criteria c = sessionFactory.getCurrentSession().createCriteria(Music.class);
		if(param==null){
			page.setPageNo(1);
			return this.entityDao.findByCriteria(page, c);
		}
		
		page.setPageNo(super.isParamNotNull(param, Page.PAGE)?Integer.valueOf((String)getParamValue(param,  Page.PAGE)):1);//查询页数
		
		if(isParamNotNull(param, "spaceIds")){
//			c.createAlias("space", "space");
			Object value=getParamValue(param, "spaceIds");
			if(value instanceof String){
				c.add(Restrictions.eq("space.id", Long.valueOf((String)getParamValue(param, "spaceIds"))));
			}else if(value instanceof List){
				c.add(Restrictions.in("space.id", (List<Long>)getParamValue(param, "spaceIds")));
			}else if(value instanceof String[]){
				c.add(Restrictions.in("space.id", (List<Long>)Arrays.asList((String[])getParamValue(param, "spaceIds"))));
			}
		}else if(isParamNotNull(param, "spaceId")){
//			c.createAlias("space", "space");
			c.add(Restrictions.eq("space.id", Long.valueOf((String)getParamValue(param, "spaceId"))));
		}
		c.addOrder(Order.desc("id"));
		return this.entityDao.findByCriteria(page, c);
	}
}
